package com.example.demo.modules.sys.controller;


import com.example.demo.config.Methods;
import com.example.demo.common.util.ResultUtil;
import com.example.demo.common.util.entity.Result;
import com.example.demo.common.util.entity.SysResultEnum;
import com.example.demo.modules.sys.dto.fileStore.FileStoreDTO;
import com.example.demo.modules.sys.entity.FileStore;
import com.example.demo.modules.sys.service.IFileStoreService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lmy
 * @since 2023-02-06
 */
@RestController
@RequestMapping("/sys/file-store")
@Api(tags = "系统模块")
public class FileStoreController {

    @Resource
    private IFileStoreService iFileStoreService;

    @Resource
    private Methods methods;

    @ApiOperation(value = "文件上传", notes = "文件上传")
    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST, consumes = "multipart/*", headers = "content-type=multipart/form-data")
    public Result<List<FileStoreDTO>> uploadFile(@RequestParam("file")MultipartFile... file) throws Exception{
        if(Objects.isNull(file)){
            return ResultUtil.info(SysResultEnum.FILE_NOT_FOUND);
        }
        List<FileStoreDTO> fileStoreDTOs = iFileStoreService.upLoadFiles(file);
        if (CollectionUtils.isEmpty(fileStoreDTOs)) {
            return ResultUtil.info(SysResultEnum.FILE_UPLOAD_ERROR);
        } else {
            return ResultUtil.success(fileStoreDTOs);
        }
    }

    @ApiOperation(value = "获取文件对象", notes = "获取文件对象")
    @RequestMapping(value = "/getFileById", method = RequestMethod.GET)
    public Result<FileStore> getFileById(@RequestParam("id") String fileId){
        return ResultUtil.success(iFileStoreService.getById(fileId));
    }

    @ApiOperation(value = "文件下载", notes = "文件下载")
    @RequestMapping(value = "/downloadFile", method = RequestMethod.GET)
    public Result downloadFile(HttpServletResponse response, String id){
        FileStore fileStore = iFileStoreService.getById(id);
        if(Objects.isNull(fileStore)){
            return ResultUtil.info(SysResultEnum.FILE_NOT_FOUND);
        }
        try {
            String path = methods.getUserDir() + File.separator + fileStore.getOriginalFile();
            File file = new File(path);
            /**文件名*/
            String fileName = fileStore.getFileName();
            /**文件后缀名*/
            String ext = fileName.substring(fileName.lastIndexOf(".") + 1).toUpperCase();
            /**流的方式下载文件*/
            InputStream is = new BufferedInputStream(new FileInputStream(file));
            byte[] buffer = new byte[is.available()];
            is.read(buffer);
            is.close();
            /**清空response*/
            response.reset();
            /**设置请求头,纯下载方式*/
            response.setContentType("application/x-msdownload");
            /**文件名加密*/
            String encodeFileName = URLEncoder.encode(fileName, "UTF8");
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(encodeFileName.getBytes()));
            response.addHeader("Content-Length", "" + file.length());
            response.setContentType("application/octet-stream");
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Cache-Control", "no-cache");
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        }catch (Exception e){
            System.out.println(e);
        }
        return ResultUtil.success(fileStore.getFileName() + "下载完成!");
    }
}

